<?php
declare (strict_types=1);

namespace app\command;

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Log;
use think\facade\Db;

class SyncActivity extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync-activity')
            ->setDescription('同步活动');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $page = 1;
        $finish = false;
        do {
            sleep(mt_rand(1, 3));
            $payload = [
                'status' => 0,
                'page' => $page,
                'pageSize' => 50,
                'page_size' => 50,
            ];
            $client = new Client();
            $url = "https://buyin.jinritemai.com/api/institution/activity/list";
            $cookies = config('app.buyin');
            try {
                $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
                $response = $client->request('GET', $url, ['query' => $payload, 'timeout' => 5, 'cookies' => $cookieJar]);
            } catch (\Exception $e) {
                Log::info('活动同步失败:' . $e->getMessage());
                $output->writeln('活动同步失败:' . $e->getMessage());
                break;
            }
            $result = json_decode($response->getBody()->getContents(), true);
            if ($result['code'] == 0) {
                $activityList = $result['data'];
                $time = time();
                if ($activityList) {
                    foreach ($activityList as $v) {
                        if ($v['status'] == 1) {
                            $online = 0;
                        } else {
                            $online = 1;
                        }
                        $specifiedShopIds = $shopTypes = $categoryIds = [];
                        $detail = $this->getActivityDetail($v['id']);

                        $shopType = isset($detail['shop_type'])?$detail['shop_type']:[];
                        if($shopType){
                            foreach ($shopType as $k1=>$v1){
                                $shopTypes[] = $k1;
                            }
                        }
                        $category = isset($detail['category'])?$detail['category']:[];
                        if($category){
                            foreach ($category as $k2=>$v2){
                                $categoryIds[] = $k2;
                            }
                        }
                        $shopInfos =  isset($v['shop_infos']) ? $v['shop_infos']: array();
                        if($shopInfos){
                            foreach ($shopInfos as $k3=>$v3){
                                $specifiedShopIds[] = $v3['shop_id'];
                            }
                        }
                        $activityExist = Db::name('activity')->where(['buyin_activity_id' => $v['id']])->field('id')->find();
                        if ($activityExist) {
                            $act = [
                                'activity_kind' => $v['activity_kind'],
                                'activity_type' => $v['activity_type'],
                                'threshold' => isset($detail['threshold'])?(int)$detail['threshold']:0,
                                'shop_type'=>json_encode($shopTypes),
                                'is_new'=>isset($detail['is_new'])?(int)$detail['is_new']:1,
                                'shop_score'=>isset($detail['shop_score'])?$detail['shop_score']:0,
                                'activity_name' => $v['activity_name'],
                                'activity_desc' => $v['activity_desc'],
                                'apply_start_time' => strtotime($v['apply_start_time']),
                                'apply_end_time' => strtotime($v['apply_end_time']),
                                'promote_start_time' => strtotime($v['promote_start_time']),
                                'promote_end_time' => strtotime($v['promote_end_time']),
                                'category' => json_encode($categoryIds),
                                'commission_rate' => $v['commission_rate'],
                                'service_rate' => $v['service_rate'],
                                'estimated_single_sale' => $v['estimated_single_sale'],
                                'wechat_id' => $v['wechat_id'],
                                'phone_num' => $v['phone_num'],
                                'online' => $online,
                                'specified_shop_ids' =>json_encode($specifiedShopIds),
                                'apply_num' => $v['apply_num'],
                                'un_audit_num' => $v['un_audit_num'],
                                'update_time' => date('Y-m-d H:i:s', $time)
                            ];
                            Db::name('activity')->where(['buyin_activity_id' => $v['id'],'is_del'=>0])->update($act);
                        } else {
                            $act = [
                                'buyin_activity_id' => $v['id'],
                                'activity_kind' => $v['activity_kind'],
                                'activity_type' => $v['activity_type'],
                                'threshold' => isset($detail['threshold'])?(int)$detail['threshold']:0,
                                'shop_type'=>json_encode($shopTypes),
                                'is_new'=>isset($detail['is_new'])?(int)$detail['is_new']:1,
                                'shop_score'=>isset($detail['shop_score'])?$detail['shop_score']:0,
                                'activity_name' => $v['activity_name'],
                                'activity_desc' => $v['activity_desc'],
                                'apply_start_time' => strtotime($v['apply_start_time']),
                                'apply_end_time' => strtotime($v['apply_end_time']),
                                'promote_start_time' => strtotime($v['promote_start_time']),
                                'promote_end_time' => strtotime($v['promote_end_time']),
                                'category' => json_encode($categoryIds),
                                'commission_rate' => $v['commission_rate'],
                                'service_rate' => $v['service_rate'],
                                'estimated_single_sale' => $v['estimated_single_sale'],
                                'wechat_id' => $v['wechat_id'],
                                'phone_num' => $v['phone_num'],
                                'online' => $online,
                                'specified_shop_ids' => json_encode($specifiedShopIds),
                                'apply_num' => $v['apply_num'],
                                'un_audit_num' => $v['un_audit_num'],
                                'create_time' => date('Y-m-d H:i:s', $time),
                                'update_time' => date('Y-m-d H:i:s', $time)
                            ];
                            Db::name('activity')->insert($act);
                        }
                    }
                }
            } else {
                Log::info('活动同步失败:' . $result['msg']);
                $output->writeln('活动同步失败:' . $result['msg']);
                break;
            }
            $totalPage = ceil($result['total'] / 50);
            $page++;
            // 当前页数 > 总页数
            if ($page > $totalPage) {
                $finish = true;
            }
        } while (!$finish);
        // 指令输出
        $output->writeln('活动同步完成');
    }

    public function getActivityDetail($activityId)
    {
        sleep(mt_rand(1, 3));
        $client = new Client();
        $url = "https://buyin.jinritemai.com/api/institution/activity/detail?activity_id=".$activityId;
        $cookies = config('app.buyin');
        try {
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            $response = $client->request('GET', $url, ['timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            Log::info("获取活动{$activityId}详情失败" . $e->getMessage());
            return [];
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if ($result['code'] == 0) {
            $detail = $result['data'];
        } else {
            $detail = [];
            Log::info("获取活动{$activityId}详情失败" . $result['msg']);
        }
       // Log::info($detail);
        return $detail;
    }

}
